<template>
  <div class="my-contextmenu"
       v-show="visible"
       :class="classes"
       :style="styles">
    <Menu v-if="visible" ref="menu" :items="data"></Menu>
  </div>
</template>
<script>
import {on, off} from 'element-ui/lib/utils/dom'
import Menu from './Menu'

export default {
  name: 'Contextmenu',
  cnName: 'Contextmenu',
  components: {
    Menu
  },
  props: {
    // 数据 [{icon, label, info, disabled, divider, children}]
    data: {
      type: Array,
      default() {
        return []
      }
    },
  },
  provide() {
    return {
      wrapper: this
    }
  },
  data() {
    return {
      visible: false,
      x: 0,
      y: 0,
      rect: null
    }
  },
  computed: {
    styles() {
      return {
        left: `${this.x}px`,
        top: `${this.y}px`,
        zIndex: this.zIndex
      }
    },
    classes() {
     return {}
    }
  },
  methods: {
    show({x, y}) {
      this.visible = true
      this.$nextTick(() => {
        const rect = this.$refs.menu.rect
        const placement = this.getPlacement(rect, x, y)
        this.x = placement.x
        this.y = placement.y
      })
    },
    getPlacement(rect, x, y) {
      const targetRect = document.body.getBoundingClientRect()
      if (rect.height + y - Math.abs(targetRect.top) >= targetRect.height) {
        y -= rect.height
      }
      if (rect.width + x - Math.abs(targetRect.left) >= targetRect.width) {
        x -= rect.width
      }
      return {
        x, y
      }
    },
    hide() {
      this.visible = false
    }
  },
  mounted() {
    on(document.body, 'click', this.hide)
  },
  beforeDestroy() {
    off(document.body, 'click', this.hide)
  }
}
</script>

<style lang="less" scoped>
.my-contextmenu {
  position: absolute;
  z-index: 1000;
  font-size: 14px;
  left: 0;
  top: 0;
}
</style>
